import React from 'react';
import {Modal, Checkbox, Row, Col, Button, message, Tooltip,Select} from 'antd';
import {injectIntl} from 'react-intl';
import axios from 'axios';
const Option = Select.Option;

class RoleManager extends React.Component {
    constructor(props) {
        super(props);
        this.menuCheckAuth = [];
        this.subAdminId = this.props.subAdminId;
        this.state = {
            roleId:'',
            options:[],
            indeterminate: true,
            checkAll: false,
            stationplainOptions: [],
            stationCheckedList: [],
            hidenStationplainOptions: []
        }
    }

    cancel = () => {
        this.props.close();
    }

    formItemLayout = {
        labelCol: {span: 1, offset: 0},
        wrapperCol: {span: 5},
    };
    componentDidMount() {
        this.getStuGroup();
    }

    getStuGroup = () => {
        axios.post('api/role/list/qry', {}).then(res => {
            if (res&&res.data) {
                this.setState(Object.assign(this.state.options, {options: res.data || []}))
            }
        })
    }
    handleCurrencyChange=(changedValue)=>{
        this.setState({
            roleId:changedValue
        })
    }

    componentWillReceiveProps(nextProps) {
        if(nextProps.selectInfo){
            this.setState({
                roleId:nextProps.selectInfo.role
            })
        }
        if (nextProps.subAdminId != undefined && nextProps.subAdminId != '' && nextProps.subAdminId != null) {
            //场站权限
            axios.post('/api/admin/right/stubGroup/list/qry', {
                subAdminId: nextProps.subAdminId
            }).then(res => {
                if (res && res.data) {
                    if (res.data.length > 0) {
                        console.log(res.data);
                        let stationCheckedList = [];
                        let stationplainOptions = [];
                        let hidenStationplainOptions = [];
                        res.data.map(function (child) {
                            hidenStationplainOptions.push(child.id);
                            let name = '';
                            let seriesArr = {};
                            if (child.name != null && child.name != '') {
                                name = child.name;
                            }
                            seriesArr['id'] = child.id;
                            seriesArr['name'] = name;
                            seriesArr['fullName'] = child.name;
                            if (child.isChosen == 1) {
                                seriesArr['isChosen'] = true;
                                stationCheckedList.push(child.id);
                            } else {
                                seriesArr['isChosen'] = false;
                            }
                            stationplainOptions.push(seriesArr);
                        });
                        this.setState({
                            stationplainOptions: stationplainOptions,
                            stationCheckedList: stationCheckedList,
                            hidenStationplainOptions: hidenStationplainOptions
                        })
                    }
                }
            });
        }
    }

    strMapToObj(strMap) {
        let obj = Object.create(null);
        for (let [k, v] of strMap) {
            obj[k] = v;
        }
        return obj;
    }

    onChangeStation = (stationCheckedList) => {
        this.setState({
            stationCheckedList,
            indeterminate: !!stationCheckedList.length && (stationCheckedList.length < this.state.stationplainOptions.length),
            checkAll: stationCheckedList.length === this.state.stationplainOptions.length,
        });
    }


    getCheckedValue = (value) => {
        //params.set(value.get("index"),value.get("checkedList"));
        console.log(value);
        this.menuCheckAuth = value;
    }

    roleSave = () => {
        axios.post('/api/admin/role/mod', {
            subAdminId: this.props.subAdminId,
            roleId: this.state.roleId
        }).then(res => {
            if (res && res.data) {
                this.props.close();
                message.success("菜单权限配置成功");
            } else {
                message.error("菜单权限配置失败");
            }
        });
    };

    /**
     * 保存权限
     */
    stationSave = () => {
        let plainOptions = this.state.hidenStationplainOptions;
        let returnArr = [];
        if (plainOptions.length > 0) {
            for (let i = 0; i < plainOptions.length; i++) {
                if (this.hasContent(plainOptions[i], this.state.stationCheckedList)) {
                    returnArr.push(plainOptions[i] + "_1");
                } else {
                    returnArr.push(plainOptions[i] + "_0");
                }
            }
        }
        axios.post('/api/admin/right/stubGroup/mod', {
            subAdminId: this.props.subAdminId,
            paramStr: returnArr.toString()
        }).then(res => {
            if (res && res.data) {
                this.props.close();
                message.success("场站权限配置成功");
            } else {
                message.error("场站权限配置失败");
            }
        });

    }

    hasContent(value, arr) {
        if (arr != undefined && arr != null && arr.length > 0) {
            for (let i = 0; i < arr.length; i++) {
                if (value == arr[i]) {
                    return true;
                }
            }
        }
        return false;
    }

    render() {
        const common = this.props.intl.messages.common;
        const checkboxStyle = {
            width: 140,
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap'
        }
        return (
            <Modal
                title={common.authorityConf}
                visible={this.props.visible}
                onCancel={this.cancel}
                cancelText={common.close}
                style={{width: '80%'}}
                footer={[<div key={1} style={{height: 22}}></div>]}
            >
                <span style={{fontWeight: 'bold', fontSize: 16}}>{common.authorityManage}：</span><br/>
                <fieldset>
                    <legend style={{fontSize: 12}}>{common.powerStationsAuth}</legend>
                    {/*<CheckboxGroup options={this.state.stationplainOptions} value={this.state.stationCheckedList} onChange={this.onChangeStation} />*/}
                    <Checkbox.Group style={{width: '100%'}} value={this.state.stationCheckedList}
                                    onChange={this.onChangeStation}>
                        <Row>
                            {
                                (this.state.stationplainOptions && this.state.stationplainOptions.length > 0) ?
                                    this.state.stationplainOptions.map((item, index) => (
                                        <Col span={8} key={item.id || index}>
                                            <Tooltip placement="top" title={item.fullName}>
                                                <Checkbox value={item.id} style={checkboxStyle}
                                                          checked={item.isChosen}>{item.name}</Checkbox>
                                            </Tooltip>
                                        </Col>
                                    )) : ''
                            }
                        </Row>
                    </Checkbox.Group>
                </fieldset>
                <br/>
                <Button type="primary" onClick={this.stationSave}>{common.powerStationSave}</Button>
                <br/>
                <br/>
                <div style={{fontWeight: 'bold', fontSize: 16,marginBottom:'1em'}}>{common.selectRole}：</div>
                <div className="stub-picker">
                    <Select
                        value={this.state.roleId}
                        optionLabelProp="children" optionFilterProp="children"
                        onChange={this.handleCurrencyChange}
                    >
                        {
                            this.state.options.map((item) =>
                                <Option value={item.id} key={item.id}>{item.name}</Option>
                            )
                        }
                    </Select>
                </div>
                <br/>
                <Button type="primary" onClick={this.roleSave}>{common.save}</Button>
            </Modal>
        );
    }
}

export default injectIntl(RoleManager);